/*
Copyright (C) 2010  Christoph Schnack, Berlin (Germany)

This file is part of Tribuit.

    Tribuit is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Tribuit is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tribuit.  If not, see <http://www.gnu.org/licenses/>.
*/
package VocabularyManagement;

import java.awt.*;
import java.awt.event.*;
import java.beans.PropertyChangeListener;
import java.util.*;

import javax.swing.*;

import GuiTools.*;
import Settings.*;
import Storage.*;

/**
 * @author Christoph Schnack
 *
 */
public class EWDFormularPanel extends MeaningFormularPanel {
	TermPanel meaningPanel;
	JTextArea noteTA,esentenceTA;
	JPanel metaPanel,ewdFormularPanel;
	JLabel phonLabel;
	SynonymsPanel synonymsPanel;
	Language LANG;
	Settings SET;
	int index;
	TribuitFrame ewdFrame;
	JTabbedPane tabs = new JTabbedPane();
	//word data
	String termClassName;
	TermClass termClass;
	Vector<String> categories;
	Vector<Term> synonyms = new Vector<Term>();
	HashMap<String,MetaElement> metaElements;
	String errorTxt="";
	
	public EWDFormularPanel(TribuitFrame parent,Settings set,TermClass tc, Vector<String> cats,int nr){
		super();
		ewdFrame = parent;
		ewdFormularPanel = this;
		categories = cats;
		termClass = tc;
		index = nr;
		LANG = set.getLanguage();
		SET = set;
		buildPanel();
	}
	
	public EWDFormularPanel(TribuitFrame parent,Settings set,Meaning m,TermClass tc, Vector<String> cats,int nr){
		super();
		ewdFrame = parent;
		ewdFormularPanel = this;
		categories = cats;
		termClass = tc;
		index = nr;
		LANG = set.getLanguage();
		SET = set;
		buildPanel();
		setUpMeaning(m);
	}
	
	private void buildPanel(){
		
		tabs.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
		
	//meaning panel
		meaningPanel = new TermPanel(SET,termClass,categories,""+index);
		LabelPanel meaningLP = new LabelPanel(LANG.getMeaning(),meaningPanel);
		meaningLP.setOpaque(false);
		
	//synonyms panel
		synonymsPanel = new SynonymsPanel();
		tabs.addTab(LANG.getSynonyms(),synonymsPanel);
		
		int jspX = 330,jspY=100;
	//meta
		metaPanel = new JPanel();
		JScrollPane mpJsp = new JScrollPane(metaPanel);
		mpJsp.setPreferredSize(new Dimension(jspX,jspY));
		setMetaPanels();
		tabs.addTab(LANG.getMeta(), mpJsp);
		
	//phonetic
		JLabel phonFront=new JLabel("["),phonTail=new JLabel("]");
		phonLabel = new JLabel("~");
		FlowLayout aLayout = new FlowLayout();
		aLayout.setHgap(5);
		JPanel phonLabelPanel = new JPanel(aLayout);
		phonLabelPanel.add(phonFront);
		phonLabelPanel.add(phonLabel);
		phonLabelPanel.add(phonTail);
		JButton phonBtn = new JButton(LANG.getEdit());
		phonBtn.addActionListener(new PhoneticListener());
		JPanel phonPanel = new JPanel();
		phonPanel.setLayout(new BoxLayout(phonPanel,BoxLayout.Y_AXIS));
		phonPanel.add(phonLabelPanel);
		phonPanel.add(phonBtn);
		phonPanel.setOpaque(false);
		JScrollPane phonJSP = new JScrollPane(phonPanel);
		phonJSP.setPreferredSize(new Dimension(jspX,jspY));
		tabs.addTab(LANG.getPhonetic(), phonJSP);
		
	//note
		noteTA = new JTextArea(3,20);
		noteTA.setLineWrap(true);
		noteTA.setWrapStyleWord(true);
		JScrollPane noteJSP = new JScrollPane(noteTA);
		noteJSP.setPreferredSize(new Dimension(jspX,jspY));
		tabs.addTab(LANG.getNote(),noteJSP);
		
	//example sentence
		esentenceTA = new JTextArea(3,20);
		esentenceTA.setLineWrap(true);
		esentenceTA.setWrapStyleWord(true);
		JScrollPane esJSP = new JScrollPane(esentenceTA);
		esJSP.setPreferredSize(new Dimension(jspX,jspY));
		tabs.addTab(LANG.getExample(), esJSP);

	//BUILDING
		this.setLayout(new BorderLayout(10, 10));
		this.add(BorderLayout.NORTH,meaningPanel);
		this.add(BorderLayout.CENTER,tabs);
	}
	
	
	public void setUpMeaning(Meaning m){
		if(termClass.hasPrefix()){
			meaningPanel.setArticle(m.getArticle());
		}
		meaningPanel.setMeaning(m.getMeaning());
		meaningPanel.setCategory(m.getCategory());
		phonLabel.setText(m.getPhonetic().equals("~")?"":m.getPhonetic());
		noteTA.setText(m.getNote().equals("~")?"":m.getNote());
		esentenceTA.setText(m.getExampleSentence().equals("~")?"":m.getExampleSentence());
		synonyms = m.getSynonyms();
		synonymsPanel.updateDisplay();
		if(m.hasMeta()){
			for(String key : termClass.getSortedKeys()){
				if(metaElements.containsKey(key)) metaElements.get(key).setValue(m.getMetaElement(key));
			}
		}
	}
	
	public void grabFocusFirstTF(){
		meaningPanel.grabFocusMeaningTF();
	}
	
	public void grabFocusFirstComponent(){
		meaningPanel.grabFocusFirstComponent();
	}
	
	public void resetAllInputs(){
		meaningPanel.resetAllData();
		noteTA.setText("");
		esentenceTA.setText("");
		phonLabel.setText("~");
		synonyms.clear();
		synonymsPanel.updateDisplay();
		if(!termClass.isEmpty()){
			for(String key : termClass.getSortedKeys()){
				if(metaElements.containsKey(key)) metaElements.get(key).setValue("");
			}
		}
	}
	
	/**
	 * Checks if any text field contains invalid input
	 * @return true if everything is valid
	 */
	public boolean checkInputs(){
		String meaning = meaningPanel.getMeaning().trim();
		if(meaning.equals("")){
			errorTxt = LANG.getMeaning()+"("+index+"): "+LANG.getInputEmpty();
			meaningPanel.putFocusOnMeaningTFAndSelectAll();
			return false;
		}
		if(!GuiTools.checkInput(meaning)){
			errorTxt = LANG.getMeaning()+"("+index+"): "+LANG.getNotThoseSigns()+": "+GuiTools.NOTALLOWEDSIGNS;
			meaningPanel.putFocusOnMeaningTFAndSelectAll();
			return false;
		}
		String note = noteTA.getText().trim();
		if(!GuiTools.checkInput(note)){
			errorTxt = LANG.getNote()+"("+index+"): "+LANG.getNotThoseSigns()+": "+GuiTools.NOTALLOWEDSIGNS;
			noteTA.requestFocus();
			noteTA.selectAll();
			return false;
		}
		String exampleSentence = esentenceTA.getText().trim();
		if(!GuiTools.checkInput(exampleSentence)){
			errorTxt = LANG.getExampleSentence()+"("+index+"): "+LANG.getNotThoseSigns()+": "+GuiTools.NOTALLOWEDSIGNS;
			esentenceTA.requestFocus();
			esentenceTA.selectAll();
			return false;
		}
		String[] keys = termClass.getKeys();
		if(keys!=null){
			for(String k : keys){
				MetaElement m = metaElements.get(k);
				String value = m.getValue().trim();
				if(m.isTextfield()){
					if(!GuiTools.checkInput(value)){
						errorTxt = LANG.getMetainformation()+" "+k+"("+index+"): "+LANG.getNotThoseSigns()+": "+GuiTools.NOTALLOWEDSIGNS;
						m.mark();
						return false;
					}
				}
			}
		}
		String article = meaningPanel.getArticle();
		if(termClass.hasPrefix()){
			if(!GuiTools.checkInput(article)){
				errorTxt = LANG.getArticle()+"("+index+"): "+LANG.getNotThoseSigns()+": "+GuiTools.NOTALLOWEDSIGNS;
				return false;
			}
		}
		return true;
	}
	
	public String getErrorMessage(){
		return errorTxt;
	}
	
	public Meaning getMeaning(){
		if(!checkInputs())return null;
		Meaning mng = new Meaning();
		String note = noteTA.getText().trim();
		if(note.equals("")) note="~";
		String exampleSentence = esentenceTA.getText().trim();
		if(exampleSentence.equals("")) exampleSentence="~";
		HashMap<String,String> meta = new HashMap<String,String>();
		String[] keys = termClass.getKeys();
		if(keys!=null){
			for(String k : keys){
				meta.put(k, metaElements.get(k).getValue().trim());
			}
		}
		String phonetic = phonLabel.getText();
		if(phonetic==null || phonetic.equals(""))phonetic="~";
		mng.setArticle(meaningPanel.getArticle().trim());
		mng.setMeaning(meaningPanel.getMeaning().trim());
		mng.setCategory(meaningPanel.getCategory());
		mng.setMeta(meta);
		mng.setNote(note);
		mng.setPhonetic(phonetic);
		mng.setExampleSentence(exampleSentence);
		mng.setSynonyms(synonyms);
		return mng;
	}
	
	public void setTermClass(TermClass t,String tc){
		termClass = t;
		termClassName = tc;
		meaningPanel.setTermClass(t);
		setMetaPanels();
		synonymsPanel.resetArticle();
		synonymsPanel.updateDisplay();
	}
	
	public void setMetaPanels(){
		metaPanel.removeAll();
		metaElements = new HashMap<String,MetaElement>();
		MetaElement me;
		if(termClass.getKeys()!=null){
			for(String key : termClass.getSortedKeys()){
				me = new MetaElement(SET,key,termClass.getValues(key));
				metaElements.put(key,me);
				metaPanel.add(metaElements.get(key));
			}
		}
	}
	
	public void setMeaningTFTitle(String title){
		meaningPanel.setMeaningLPTitle(title);
	}
	
	class PhoneticListener implements ActionListener{
		public void actionPerformed(ActionEvent e){
			EditPhoneticDialog pd = new EditPhoneticDialog(ewdFrame,SET,phonLabel.getText());
			if(pd.getResult()!=null)phonLabel.setText(pd.getResult());
		}
	}
	
	public void openSynonymsDialog(){
		synonymsPanel.openDialog();
	}
	class SynonymsPanel extends JPanel{
		JPanel synonymsDisplayPanel;
		JButton editBTN;
		public SynonymsPanel(){
			super();
			this.setOpaque(false);
			buildSynonymsPanel();
		}
		public void buildSynonymsPanel(){
			synonymsDisplayPanel = new JPanel();
			synonymsDisplayPanel.setLayout(new BoxLayout(synonymsDisplayPanel,BoxLayout.Y_AXIS));
			editBTN = new JButton(LANG.getEdit());
			editBTN.addActionListener(new MaEditBTNListener());
			JPanel btnPanel = new JPanel();
			btnPanel.add(editBTN);
			this.add(synonymsDisplayPanel);
			this.add(btnPanel);
		}
		
		public void openDialog(){
			editBTN.doClick();
		}
		
		public void resetArticle(){
			if(!synonyms.isEmpty()){
				for(int i=0;i<synonyms.size();i++){
					if(termClass.hasPrefix()){
						if(termClass.getPreFixVal()!=null) synonyms.elementAt(i).setArticle(termClass.getPreFixVal().firstElement());
					}
					else{
						synonyms.elementAt(i).setArticle("");
					}
				}
			}
		}
		
		public void updateDisplay(){
			synonymsDisplayPanel.removeAll();
			if(synonyms.size()>0){
				for(int i=0;i<synonyms.size();i++){
					JLabel label = new JLabel(i+2+".: "+synonyms.elementAt(i).getFullTerm());
					Font f = label.getFont();
					label.setFont(new Font(Font.SERIF,Font.PLAIN,f.getSize()));
					synonymsDisplayPanel.add(label);
				}
			}
			ewdFrame.repaint();
		}
		
		class MaEditBTNListener implements ActionListener{
			public void actionPerformed(ActionEvent e){
				EditSynonymsDialog esd = new EditSynonymsDialog(ewdFrame,SET,termClass,categories,synonyms);
				if(!esd.getAborted() && esd.getResult()!=null){
					synonyms = esd.getResult();
					synonymsPanel.updateDisplay();
				}
			}
		}
	}
}
